
function initPage(callback) {
	$(document).unbind("scroll");
	/*setJSAPI().then(function() {
		homeShare(callback)
	})*/
}

function homeShare(callback) {
	$.get(base_url + "wechat/pages/yiqizhuan.json", function(e) {
		makeShare(e.title, e.desc, e.shareUrl, e.imgUrl);
		wx.hideMenuItems({
			menuList: ["menuItem:copyUrl", "menuItem:originPage", "menuItem:favorite", "menuItem:openWithQQBrowser", "menuItem:openWithSafari", "menuItem:share:email"]
		})
		if(callback){
			callback(e);
		}
	})
}
function shangjiaShare() {
	 return new Promise(function(resolve, reject) {
		$.get(base_url + "wechat/pages/lingxianjin.json", function(data) {
			var e=data.data;
			console.log(e)
			wx.ready(function() {
				makeShare(e.title, e.desc, e.url, e.img);
				wx.hideMenuItems({
					menuList: ["menuItem:copyUrl", "menuItem:originPage", "menuItem:favorite", "menuItem:openWithQQBrowser", "menuItem:openWithSafari", "menuItem:share:email"]
				})
			});
			resolve(e);
		})
	});
}
function loadActivity(_this, tbName,tbindex) {
	return new Promise(function(resolve, reject) {
		ajaxGet("firework/bonus/activity.json", {}, function(data) {
			var active = data.data;
			actId = active.id;
			active.tbname = tbName;
			if(tbindex==1){
				active.levels=active.jiangjin.levels;
				active.thname1="奖项";
				active.thname2="奖金";
			}else{
				active.levels=active.butie.levels;
				active.thname1="嘉宾";
				active.thname2="补贴";
			}
			$(_this).find("#action").append(template("tpl_jiangxiang", active));
			resolve(active);
		})
	})
}
var actId = 0,
	baobei_top = 0,totalNumber=0;
$(function() {
	router = new Router({
		container: "#container",
		enterTimeout: 250,
		leaveTimeout: 250
	});
	var fenqian={
		url: "/fenqian",
		className: "fenqian",
		render: function () {
			setTitle("分钱");
			return new Promise(function (resolve, reject){
				ajaxGet("firework/bonus/incomes.json",{},function(data){
					data.data["nav"]=2;
					content_data=data;
					resolve(template("tpl_fenqian", data.data));
				},function(){
					reject();
				});
			});
		},
		bind: function () {
			var _this=this;
			if(content_data.data.inviteCount>0){
				$(_this).find('#baobeilist').show();
				pullLoadData(_this,'#baobeilist','#baobeilist .list',"firework/invites/progeny.json","tpl_mymoney_invites",{},function(data){
				},"tpl_doc_list");
			}else{
				fullDocument(_this);
				emptyDocContent(content_data,$(_this).find("#doclist"),"tpl_doc_list");
			}
			
		}};
	router.push(fenqian);
	var content_data;
	var zhuanqian={
		url: "/zhuanqian",
		className: "fenqian",
		render: function () {
			setTitle("赚钱");
			return new Promise(function (resolve, reject){
				ajaxGet("service/vips/income.json",{},function(data){
					data.data["nav"]=4;
					data.data["spreadMoney"]=data.data.money;
					content_data=data;
					resolve(template("tpl_zhuanqian", data.data));
				},function(){
					reject();
				});
			});
		},
		bind: function () {
			var _this=this;
			if(content_data.data.count>0){
				$(_this).find('#baobeilist').show();
				pullLoadData(_this,'#baobeilist','#baobeilist .list',"service/vips/lists.json","tpl_mymoney_invite_stores2",{},function(data){
				},"tpl_doc_list");
			}else{
				fullDocument(_this);
				emptyDocContent(content_data,$(_this).find("#doclist"),"tpl_doc_list");
			}
			//打开公众号二维码，长按方便关注
			$(_this).find(".btn_focus").click(function(){
				$(_this).find("#ecodeDialog").show()
			});
			$(_this).find(".btn_close").click(function(){
				$(_this).find("#ecodeDialog").hide()
			});
			
		}};
	router.push(zhuanqian);
	var baobao = {
		url: "/",
		className: "home",
		render: function () {
			return new Promise(function (resolve, reject){
				ajaxGet("firework/bonus/activity.json",{},function(data){
					actId=data.data.id;
					totalNumber=data.data.mycount;
					setTitle("领现金")
					data.data["nav"]=1;
					uid=data.data.uid;
					resolve(template("tpl_baobao", data.data));
				},function(){
					reject();
				});
			});
		},
		bind: function () {
			var _this=this;
			initPage();
			//默认领码一次
			if(uid>0){
				//只有登录状态，才允许领码
				ajaxGet("firework/bonus/receive.json", {
					id: actId
				}, function (data) {
					var str="今天抽奖码已领取，";
					$(_this).find("#yilingqu").html(str);
					$(_this).find("#totalNumber").html(data.scount);
				})
			}
		}
	};
	var baohao={
		url: "/baohao/:id",
		className: "baohao",
		render: function () {
			actId=this.params.id;
			return setTitle("本期中奖详细"), template("tpl_baohao", {})
		},
		bind: function () {
			var _this = this;
			function loadMyNumbers(){
				return new Promise(function(resolve, reject)  {
					ajaxGet("firework/bonus/numbers/"+actId+".json",{"status":2},function(data){
						$(_this).find("#numbers").html(template("tpl_receive_numbers",data));
						resolve();
					});
				})
			};
			Promise.all([loadActivity(_this, "领宝码", 1),loadMyNumbers()]).then(function (actinfo) {
				pullLoadData(_this,'#otherNumbers','#otherNumbers ul',"firework/bonus/fnumbers/"+actId+".json","tpl_receive_number_data",{"status":1},function(data){
					$(_this).find("#gxnumber").html(data.count).parent().show();
				});
			});
			//打开公众号二维码，长按方便关注
			$(_this).find(".btn_focus").click(function(){
				$(_this).find("#ecodeDialog").show()
			});
			$(_this).find(".btn_close").click(function(){
				$(_this).find("#ecodeDialog").hide()
			});
	}};
	router.push(baohao);	
	var baby={
		url: "/baby/:id",
		className: "baohao",
		render: function () {
			actId=this.params.id;
			return setTitle("开奖补贴详情"), template("tpl_baby", {id:actId})
		},
		bind: function () {
			var _this = this;
			$(_this).addClass("pa_baby");
			loadActivity(_this, "开奖宝贝", 2).then(function(){})
	}};
	router.push(baby);	
	var share={
		url: "/share",
		className: "baohao",
		render: function () {
			actId=this.params.id;
			return setTitle("分享活动"), template("tpl_baoma_share", {})
		},
		bind: function () {
			var _this = this;
			//加载攻略说明
			ajaxGet("utils/docs/articles/10095.json", {}, function (data) {
				$(_this).find("#docs").html(template("tpl_gonglue_up", data))
			})
	}};
	router.push(share);	
	var vips={
		url: "/vips",
		className: "vippanel",
		render: function () {
			actId=this.params.id;
			return setTitle("会员折扣"), template("tpl_vip", {nav:3})
		},
		bind: function () {
			var _this = this;			
			ajaxGet('firework/adplace/findbysiteid.json', {id: 110}, function(data){
				$(_this).find("#vip_tab .weui-navbar-scroll").html(template("tpl_vip_category",data));
				tabPullLoadData(_this, '#vip_tab .weui-navbar__item', 
				'#tab_panel_0 .weui-media-box_text', base_url+"firework/goods/findbyadplace.json",
				"tpl_vip_goods",
				{id:data.data[0]["id"]},function(data,tabPageName,itemIndex){
					console.log(tabPageName,itemIndex)
				},"get","weui-bar__item_on",false);
			});
			$('#tab_panel_0').delegate('.goods', 'click', function(ev){
				var objj = {};
				objj.id = $(this).attr('id');				
				objj.shopid = $(this).attr('shopid');
				objj.latitude = $(this).attr('latitude');
				objj.longitude = $(this).attr('longitude');					
				go('salesman.html#/goods_details/'+ $(this).attr('id'));
			});
	}};
	router.push(vips);	
	
	var income = {
		url: '/income',
		className: 'income',
		render: function() {
			setTitle("我的收益");
			return new Promise(function (resolve, reject){
			//查询中奖奖金
				ajaxGet("firework/bonus/income.json",{},function(data){
					data.data["nav"]=4;
					resolve(template("tpl_income", data.data));
				},function(){
					reject();
				});
			});
		},
		bind: function() {
			var _this = this;
			//滚动我的关联用户列表和关联的商家列表
			tabPullLoadData(_this, '#income_tab .weui-navbar__item', 
			'#tab_panel_0 .weui-media-box_text', 
			[base_url+"firework/invites/progeny.json",
			base_url+"firework/invites/progenystore.json"],
			["tpl_mymoney_invites",
			"tpl_mymoney_invite_stores"],
			{status:2},function(data,tabPageName,itemIndex){
				console.log(tabPageName,itemIndex)
			},"get","weui-bar__item_on",false,"tpl_doc_content");
		}
	};
	router.push(income);
	var baoma = {
		url: "/baoma",
		className: "baoma",
		render: function () {
			return setTitle("领宝码"), template("tpl_baoma", {})
		},
		bind: function () {
			var _this = this;
			initPage();
			loadActivity(_this, "领宝码", 1).then(function (actinfo) {
				ajaxGet("firework/bonus/receive.json", {
					id: actinfo.id
				}, function (data) {
					$(_this).find("#number_panel").html(template("tpl_lingjiangma", data))
				})
			});
			//加载攻略说明
			ajaxGet("utils/docs/articles/10095.json", {}, function (data) {
				$(_this).find("#docs").html(template("tpl_gonglue", data))
			})
		}
	};

	var baobei = {
		url: "/baobei",
		className: "baobei",
		render: function () {
			return setTitle("开奖宝贝"), template("tpl_baobei", {})
		},
		bind: function () {
			var _this = this;
			$(document).unbind("scroll");
			var wh = $(window).height();
			var ww = $(window).width();
			Promise.all([loadActivity(_this, "开奖宝贝", 2), getLocation(true), setJSAPI()]).then(function () {
				homeShare();
				baobei_top = $("#coupon_tab").position().top - 25;
				$(_this).children().each(function (ind, ele) {
					if (ind < 3) {
						baobei_top += $(this).height();
					}
				});
				//获取微信经度纬度
				tabPullLoadData(_this, "#coupon_tab .weui-navbar__item",
					"#coupon_tab .weui-tab__panel",
					base_url + "firework/bonus/joinshops/" + actId + ".json", "tpl_home_desc_stores", {
						level: 1,
						order: "geo",
						longitude: longitude,
						latitude: latitude
					},
					function () {
					}, "get", "weui-bar__item_on", true);
				//选项卡点击切换
				$(_this).find("#coupon_tab .weui-navbar__item").click(function () {
					$(_this).find(".weui-tab__panel").css("min-height", wh - 2);
					scrollTop3(baobei_top + 1);
					$(_this).find(".shuihou").removeAttr("style").removeClass("open");
				});
				//绑定滑动事件
				$(document).scroll(function () {
					var i = $(this).scrollTop();
					if (i > baobei_top) {
						$(_this).find("#coupon_tab .weui-navbar").addClass("fix");
						$(_this).find(".shuihou").addClass("fix");
					} else {
						$(_this).find("#coupon_tab .weui-navbar").removeClass("fix");
						$(_this).find(".shuihou").removeClass("fix");
						$(_this).find(".shuihou").removeAttr("style").removeClass("open");
					}
				})
			});
			//底部弹起区域
			$(_this).find(".shuihou").on("click", ".buttons", function () {
				var wh = $(window).height();
				var pare = $(this).parent();
				if (!$(pare).hasClass("open")) {
					$(pare).css("top", wh - $(pare).height() - 10).addClass("open");
					return false;
				}
				//执行默认的点击事件
			}).on("click", ".gas", function () {
				//跳转加油站
				go("/web/baobao/business.html#/gas");
				return false;
			}).on("click", ".more", function () {
				//跳转宝店
				go("#/baodian");
				return false;
			}).on("click", function () {
				$(this).removeAttr("style").removeClass("open");
				return false;
			});
			var height = ww / 750 * 120;
			$(_this).find(".shuihou .empty").css("height", height)
		}
	};
	var stores = {
		url: "/stores/:id",
		className: "baobei",
		render: function () {
			actId=this.params.id;
			return setTitle("开奖宝店"), template("tpl_stores", {id:actId})
		},
		bind: function () {
			var _this = this;
			$(_this).addClass("withStore");
			Promise.all([getLocation(true), setJSAPI()]).then(function () {
				baobei_top=0;
				//获取微信经度纬度
				tabPullLoadData(_this, "#coupon_tab .weui-navbar__item",
					"#coupon_tab .weui-tab__panel",
					base_url + "firework/bonus/joinshops/" + actId + ".json", "tpl_home_desc_stores", {
						level: 1,
						order: "geo",
						longitude: longitude,
						latitude: latitude
					},
					function () {
					}, "get", "weui-bar__item_on", true);
			});
			
		}};
	router.push(stores);

	var baodian = {
		url: "/baodian",
		className: "baodian",
		render: function () {
			return setTitle("开奖宝店"), template("tpl_baodian", {})
		},
		bind: function () {
			var _this = this;
			var wh = $(window).height();
			//initPage();
			$(document).unbind("scroll");
			shangjiaShare().then(function(){
				console.log("获取分享物资完成")
				setJSAPI().then(function() {
					console.log("注册授权完成")
				})
			})
			
			$(".share_friend").on('click',function(){
				$(".shareToast").show();
			})
			$(".shareBtn").on('click',function(){
				$(".shareToast").hide();
			})
			var tabNames = (["收入一", "收入二", "收入三", "收入四", "收入五", "收入六"]);
			ajaxGet("utils/docs/articles/10096.json", {}, function (data) {
				baobei_top = 55;
				$(_this).children().each(function (ind, ele) {
					if (ind < 2) {
						baobei_top += $(this).height();
					}
				});
				$(_this).find(".swiper-container").css("min-height", wh - 2);
				$(_this).find("#doc_swiper .swiper-wrapper").html(template("tpl_doc_swiper", data));
				new Swiper("#doc_swiper", {
					pagination: {
						el: ".weui-navbar",
						type: "bullets",
						clickable: !0,
						bulletClass: "weui-navbar__item",
						bulletActiveClass: "weui-bar__item_on",
						renderBullet: function (e, i) {
							return '<div class="' + i + '">' + tabNames[e] + "</div>"
						}
					},
					on: {
						slideChange: function () {
							if(!isSip){
								scrollTop3(baobei_top + 1)
							}
						}
					}
				});
				var isSip=false;
			});
		}
	};
	__inline('citys.js');
	var spread = {
		url: "/spread",
		className: "spread",
		render: function () {
			return setTitle("宝店客"), template("tpl_spread", {})
		},
		bind: function () {
			//微信定位获取经纬度
			Promise.all([getLocation(true), setJSAPI()]).then(function (res) {
				var data = res[0];
				latitude = data.latitude;
				longitude = data.longitude;
				ajaxGet('utils/ip/citybydist.json', {
					longitude: longitude,
					latitude: latitude,
				}, function (data) {
					if (data.code === 200) {
						$('.area_activity').html(template("tpl_dingwei", data));
					}
				})
			})
			//更换地区
			$(".changes").on('click', function () {
				$(".provinces").css('display', 'flex');
			})
			//关闭
			$(".provinces").on('click', function () {
				$(".provinces").css('display', 'none');
			})
			var str = '';
			var str2 = '';
			var str3 = '';
			var value1 = '';
			var value2 = '';
			var value3 = '';
			var province_id = 0;
			var city_id = 0;
			var area_id = 0;
			var isThree = true; //是否有三级820000,810000,500000,110000,120000,310000 这6个只有两级联动
			ajaxGet('utils/region/province.json', {}, function (data) {
				if (data.code === 200) {
					for (var i = 0; i < data.data.length; i++) {
						str += '<p class="' + data.data[i].id + '">' + data.data[i].name + '</p>';
					}
					$("#sel_p").append(str);
					$("#sel_p p").on('click', function (event) {
						event.stopPropagation();
						isThree = true;
						$(this).addClass('red1');
						$(this).siblings().removeClass('red1');
						value1 = $(this).html();
						province_id = $(this).attr('class').split(' ')[0];
						var p_id = $(this).attr('class').split(' ')[0];
						if (p_id === '820000' || p_id === '810000' || p_id === '500000' || p_id === '110000' || p_id === '120000' || p_id === '310000') {
							isThree = false;
						}
						ajaxGet('utils/region/city.json', {
							id: $(this).attr('class').split(' ')[0]
						}, function (data2) {
							if (data2.code === 200) {
								$("#sel_c").empty();
								str2 = '';
								$("#sel_a").empty();
								str3 = '';
								for (var i = 0; i < data2.data.length; i++) {
									str2 += '<p class="' + data2.data[i].id + '">' + data2.data[i].name + '</p>';
								}
								$("#sel_c").append(str2);
								$("#sel_c").css('borderRight', '1px solid #efefef');
								$("#sel_c p").on('click', function (event) {
									event.stopPropagation();
									value2 = $(this).html();
									$(this).addClass('red2');
									$(this).siblings().removeClass('red2');
									city_id = $(this).attr('class').split(' ')[0];
									//是否有三级
									if (isThree) {
										ajaxGet('utils/region/city.json', {
											id: $(this).attr('class').split(' ')[0]
										}, function (data3) {
											if (data3.code === 200) {
												$("#sel_a").empty();
												str3 = '';
												for (var i = 0; i < data3.data.length; i++) {
													str3 += '<p class="' + data3.data[i].id + '">' + data3.data[i].name + '</p>';
												}
												$("#sel_a").append(str3);
												$("#sel_a p").on('click', function (event) {
													event.stopPropagation();
													value3 = $(this).html();
													$(this).addClass('red3');
													$(this).siblings().removeClass('red3');
													area_id = $(this).attr('class').split(' ')[0];
													$(".locations").html(value2 + ',' + value3);
													$(".areas").html(value3);
													var strs = '';
													strs = '&province=' + province_id + '&city=' + city_id + '&country=' + area_id;
													//宝店进度 一月
													ajaxPost2('firework/schedule/month.json' + params + strs, {}, function (data) {
														if (data.code === 200) {
															$(".data_lists").append(template("tpl_month_process", data));
														}
													})
													setTimeout(function () {
														$(".provinces").css('display', 'none');
													}, 500)
												})
											}
										})
									} else {
										$(".locations").html(value1 + ',' + value2);
										$(".areas").html(value2);
										setTimeout(function () {
											$(".provinces").css('display', 'none');
										}, 500)
									}
								})
							}
						})
					})
				}
			})
			//立即报名
			$(".sign_up").on('click', function () {
				ajaxPost('firework/schedule/signup.json', {}, function (data) {
					if (data.code === 200) {
						showInfoMsg('报名成功');
					} else {
						showErrorMsg('报名失败');
					}
				})
			})
		}
	};
	router.push(baodian).push(baoma).push(baobei).push(baobao).push(spread).setDefault("/").init()
})

window.chartColors = {
	red: 'rgb(255, 99, 132)',
	orange: 'rgb(255, 159, 64)',
	yellow: 'rgb(255, 205, 86)',
	green: 'rgb(75, 192, 192)',
	blue: 'rgb(54, 162, 235)',
	purple: 'rgb(153, 102, 255)',
	grey: 'rgb(201, 203, 207)',
	white:'rgb(255,255,255)'
};
var chartOptions={
	responsive: true,
	legend: {
		display:false,
	},
	tooltips: {
		displayColors:false,
		bodyFontColor:'#000',
		backgroundColor:'rgba(205, 193, 229, 0.91)',
        callbacks: {
        	title:function(tooltipItem){
        		return '';
        	},
            label: function(tooltipItem, data) {
                return (Math.round(tooltipItem.yLabel * 100) / 100)+"元";
            }
        }
 }
}

$(function(){
	//默认分享
	setJSAPI(10384,10106).then(function(){
		console.log("默认分享初始化完成")
	})
})